<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-breadcrumb>
              <a-breadcrumb-item href="">
                <a-icon type="home" />
                <span>首页</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <a-icon type="gift" />
                <span>物资管理</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <span>
                <template v-if="this.id !== ''"> <a-icon type="edit" />物资编辑</template>
                  <template v-else> <a-icon type="folder-add" />物资添加</template>
                </span>
              </a-breadcrumb-item>
            </a-breadcrumb>
          </a-col>
          <a-col :span="24">&nbsp;</a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form-model :model="formData">
        <a-row :gutter="24">
          <a-col :span="16">
            <a-form-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-button-group>
                  <a-button type="primary" @click="goBack"> <a-icon type="left" />返回 </a-button>
                  <a-button type="primary"  @click="toSave"> 保存<a-icon type="right" /> </a-button>
                </a-button-group>
            </a-form-item>
          </a-col>
          <a-col :span="8" :style="{ textAlign: 'right' }">
            <a-form-item>
              <a-button-group>
                <a-button type="primary" @click="toAudit">
                  审批
                </a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item style="display: none;width:0px;" :labelCol="labelCol" :wrapperCol="wrapperCol"  label="id">
              <a-input v-model="formData.id" />
            </a-form-model-item>
            <a-form-model-item label="申请单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.applyCode" :disabled="disabledOne" placeholder="请输入申请单号"></a-input>
            </a-form-model-item>
          <a-form-model-item label="申请名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-model="formData.applicantName" placeholder="请输入申请名称"></a-input>
          </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.departName" :disabled="disabledOne" placeholder="请输入申请部门"></a-input>
            </a-form-model-item>
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.createBy" :disabled="disabledOne" placeholder="请输入申请人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择申请时间" v-model="formData.applyTime" showTime
                      :dateFormat="dateFormat"
                      :disabled="disabledOne" style="width: 100%"/>
            </a-form-model-item>
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.status" :disabled="disabledOne" placeholder="请输入状态"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>

    <!-- table区域-begin -->
    <div>

      <a-button class="editable-add-btn" @click="handleAdd">
        添加
      </a-button>
      <a-table ref="table" bordered :data-source="dataSource" :columns="columns">
        <template slot="action" slot-scope="text, record">
          <a @click="() => handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => deleteNow(record)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>

    </div>
    <mms-material-code-details-modal ref="modalForm" @ok="saveOk"></mms-material-code-details-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@lone/lone-vue/src/utils/mixin'
  import { JEditableTableMixin } from '@lone/lone-vue/src/mixins/JEditableTableMixin'
  import { FormTypes } from '@lone/lone-vue/src/utils/JEditableTableUtil'
  import JEditableTable from '@lone/lone-vue/src/components/jeecg/JEditableTable'
  import JDate from '@lone/lone-vue/src/components/jeecg/JDate'
  import { postAction, putAction, getAction } from '@lone/lone-vue/src/api/manage'
  import Vue from 'vue'
  import JTreeSelect from '@lone/lone-vue/src/components/jeecg/JTreeSelect'
  import MmsMaterialCodeDetailsModal from './modules/MmsMaterialCodeDetailsModal'

  export default {
    name: 'MmsMaterialCodeDetailsList',
    mixins:[JEditableTableMixin, mixinDevice],
    components: {
      JDate,
      JEditableTable,
      JTreeSelect,
      MmsMaterialCodeDetailsModal
    },
    props:{
      //判断是编辑还是新增
      status:{
        type:String,
        required:false
      },
      //判断是编辑Id
      id:{
        type:String,
        required:false
      },
    },
    watch:{
      status: {
        handler(newVal, oldVal) {
          this.loadFormData()
        },
        immediate: true
      }
    },
    data () {
      return {
        selectValue: '',
        description: 'mms_material_code_details管理页面',
        top: 10,
        dateFormat: 'YYYY-MM-DD HH:mm:ss',
        disabledAll: false,
        disabledOne: false,
        editingKey: '',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '物资编码',
            dataIndex: 'code'
          },
          {
            title: '物资名称',
            dataIndex: 'name'
          },
          {
            title: '规格',
            dataIndex: 'specs'
          },
          {
            title: '型号',
            dataIndex: 'model'
          },
          {
            title: '计量单位',
            dataIndex: 'unit'
          },
          {
            title: '物资分类',
            dataIndex: 'classifyCode'
          },
          {
            title: '生产厂商',
            dataIndex: 'manufacturer'
          },
          {
            title: '品牌',
            dataIndex: 'brand'
          },
          {
            title: '操作',
            dataIndex: 'id',
            scopedSlots: { customRender: 'action' }
          }
        ],
        dataSource: [],
        formData:{},
        url: {
          list: "/base/mmsMaterialCodeDetails/list",
          delete: "/base/mmsMaterialCodeDetails/delete",
          deleteBatch: "/base/mmsMaterialCodeDetails/deleteBatch",
          exportXlsUrl: "/base/mmsMaterialCodeDetails/exportXls",
          importExcelUrl: "base/mmsMaterialCodeDetails/importExcel"
        },
        dictOptions:{},
      }
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      loadFormData() {
        let that = this
        that.formData.applyTime = Vue.prototype.$formatDate()
        that.formData.status = '新建'
        this.dataSource = [];
        getAction('/base/mmsMaterialCode/getUserInfo', {}).then((res) => {
          if (res.success) {
            let result = res.result
            if (result) {
              this.$set(this.formData, 'departName', result['orgName'])
              this.$set(this.formData, 'createBy', result['realname'])
            }
          }
        })
        that.loadMaterialUnit()
        if ( this.id !== '@ADD@') {
          let paramsObject = { id: this.id }
          getAction('/base/mmsMaterialCode/queryById', paramsObject).then((res) => {
            if (res.success) {
              let result = res.result
              if (result) {
                for (let p in result) {
                  if (p === 'details') {
                    const records = result[p]
                    for(let r in records){
                      let newData = records[r];
                      this.dataSource.push(newData);
                    }
                  } else {
                    this.$set(this.formData, p, result[p])
                  }
                }
              }
            }
          })
        }
        that.disabledOne = true
      },
      saveOk(record) {
        let that = this;
        if (record && record.id) {
          const newData = [...this.dataSource];
          const target = newData.filter(item => item.id === record.id)[0];
          newData[newData.indexOf(target)] = record;
          this.dataSource = newData;
        }else{
          record['id'] = '';
          this.dataSource.push(record);
        }
      },
      loadMaterialUnit(){
        let that = this;
        getAction('/base/mmsMaterialUnit/list', {}).then((res) => {
          if (res.success) {
            let result = res.result;
            if (result) {
              const options = [];
              for(let r in result.records){
                options[r] = { title: result.records[r]['name'], value: result.records[r]['code'] };
                if(r == 0){
                  that.columns[4].defaultValue = result.records[r]['code'];
                }
              }
              that.columns[4].options = options
            }
          }
        })
      },
      goBack(){
        this.$emit('prevStep')
      },
      handleEdit: function (record, params) {
        this.$refs.modalForm.edit(record, params);
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
      },
      handleAdd: function (params) {
        this.$refs.modalForm.add(params);
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
      },
      handleSelectRowChange(selectedKeys) {
        this.selectedKeys = selectedKeys;
        console.log(selectedKeys);
      },
      toAudit(){
        let that = this, id = that.formData.id;
        getAction('/base/mmsMaterialCode/audit', {id: id}).then((res) => {
          if (res.success) {
            let result = res.result;
            if (result) {
              that.redirect(id)
            }
          }
        })
      },
      toSave(){
        let that = this, paramsObject = {details: this.dataSource}, id = that.formData.id;
        for(let param in this.formData){
          this.$set(paramsObject, param, this.formData[param]);
        }
        let action = postAction, url = 'base/mmsMaterialCode/add';
        if(paramsObject.hasOwnProperty('id') && paramsObject['id']){
          url = 'base/mmsMaterialCode/edit';
          action = putAction;
        }
        action(url, paramsObject).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            let result = res.result;
            if (result) {
              that.redirect(result['id'])
            }
          } else {
            this.$message.warning(res.message);
            that.redirect(id);
          }
        }).finally(() => {
        })
       /* let that = this, {  error, values } = this.$refs.table.getValuesSync({ validate: true});
        if (!(error === 0)) {
          return this.$message.warning("验证不成功，红框数据不能为空!")
        }
        if (values.length > 0) {
          let paramsObject = {details: values};
          for(let param in this.formData){
            this.$set(paramsObject, param, this.formData[param]);
          }
          let action = postAction, url = 'base/mmsMaterialCode/add';
          if(paramsObject.hasOwnProperty('id') && paramsObject['id']){
            url = 'base/mmsMaterialCode/edit';
            action = putAction;
          }
          action(url, paramsObject).then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              this.$emit('ok');
              if(res.result){
                for(let p in res.result) {
                  if(p === 'details'){
                    const records = res.result[p];
                    for(let r in records){
                      records[r].editable = false;
                    }
                    that.dataSource = records;
                  }else{
                    this.$set(this.formData, p, res.result[p]);
                  }
                }
              }
            } else {
              this.$message.warning(res.message);
            }
          }).finally(() => {
          })
        } else {
          this.$message.success("请选择最少一条新增数据！");
        }*/
      },
      redirect(id){
        let that = this;
        that.$emit("prevStep");
        that.$emit("nextStep",{id:id,status: ''})
      },
      deleteNow(record){
        let that = this;
        this.dataSource.splice(this.dataSource.indexOf(record),1);
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  .editable-row-operations a {
    margin-right: 8px;
  }
</style>